#!/bin/sh
###################################################################################
#
# (c) Copyright 2014 Hewlett-Packard Development Company, L.P. All rights reserved.
#
# @since 3.2
# @author bow
# @author Yang, Lin
###################################################################################

#Please modify the following parameters for your env
PARAM_FILE=.param.tmp
RESULT_FILE=.result.txt
JAVA_HOME=$JAVA_HOME

# arguments from properties file/stream
SSH_USER=
EIUM_HOME=
EIUM_USER=
EIUM_PWD=
SESSION_SERVERS=
TIMEOUT=
START_DELAY=
BIZ_SERVICE_STATUS=

# scope: shell
EIUM_SECURITY=
CLASSPATH=

#===================== Functions

# getProperty
# $1- content of properties file as string
# $2- property name
getProperty()
{
    PROP_VALUE=`echo "$1"|grep -w $2|awk -F= '{print $2}'`
    if [[ "$?" != "0" ]]; then
        PROP_VALUE=""
    fi
    echo "$2=$PROP_VALUE"
}

# readProperty
# $1- content of properties file as string
readProperty()
{
    # SSH user
    getProperty "$1" SSH_USER
    SSH_USER=$PROP_VALUE

    # eIUM instance
    getProperty "$1" EIUM_HOME
    EIUM_HOME=$PROP_VALUE

    # session servers
    getProperty "$1" SESSION_SERVERS
    SESSION_SERVERS=($PROP_VALUE)
    SESSION_SERVERS=`echo $SESSION_SERVERS | awk -F':' '{print $2}'`

    # timeout
    getProperty "$1" TIMEOUT
    TIMEOUT=$PROP_VALUE

    getProperty "$1" START_DELAY
    START_DELAY=$PROP_VALUE

    # security
    getProperty "$1" EIUM_USER
    EIUM_USER=$PROP_VALUE
    getProperty "$1" EIUM_PWD
    EIUM_PWD=$PROP_VALUE
    if [ "$EIUM_USER" != "" ]; then
        EIUM_SECURITY=" login -user $EIUM_USER -password $EIUM_PWD -- "
    fi

    # biz_service_status
    getProperty "$1" BIZ_SERVICE_STATUS
    BIZ_SERVICE_STATUS=$PROP_VALUE

    echo "JAVA_HOME=$JAVA_HOME"

    getClasspath
}

initParamFile()
{
    rm -f $PARAM_FILE
	echo $EIUM_USER > $PARAM_FILE
	echo $EIUM_PWD >> $PARAM_FILE
}

getClasspath()
{
    # GR lib
    for ff in $TOOL_ROOT/../../lib/*.jar
    do
        CLASSPATH="$ff:$CLASSPATH"
    done

    # eIUM lib
    for ff in $EIUM_HOME/lib/*.jar
    do
        if [[ "$ff" != "$EIUM_HOME/lib/slf4j-api.jar" && "$ff" != "$EIUM_HOME/lib/siulogging-slf4j.jar" ]]
        then
            CLASSPATH="$ff:$CLASSPATH"
        fi
    done

    # eIUM plugins: latest com.hp.usage.jmx_x.y.z
    local PLUGINS_JMX=`ls $EIUM_HOME/plugins -r | grep com.hp.usage.jmx_ | head -1`
    CLASSPATH="$EIUM_HOME/plugins/$PLUGINS_JMX/jdmkrt.jar:$EIUM_HOME/plugins/$PLUGINS_JMX/jmx.jar:$CLASSPATH"
}

# assertUser
# $1- username
# $2- "not" mean not input user can be continue. Default only input user can be continue.
assertUser()
{
    if [ "$LOGNAME" = "$1" ];    then
        if [ "$2" == "not" ]; then
            echo "Cannot be running in $1."
            exit 1
        fi
    else
        if [ "$2" != "not" ]; then
            echo "Cannot be running in $1."
            exit 1
        fi
    fi
}

##########################
TOOL_ROOT=`dirname $0`
TOOL_TMP_DIR=$TOOL_ROOT/../../temp
NOW=`date +%Y%m%d%H%M%S`

assertUser root not

showResultYesNo()
{
    # $1 - prompt; $2 - Result string
    echo -n "$1"
    if [ "$2" = "" ] ; then
        echo "No"
    else
        echo "Yes"
    fi
}

# $1- hostname
# $2- session server name
# $3- output
checkServerStatus()
{
    RESULT_SERVER=$($JAVA_HOME/bin/java -DGRHome=$TOOL_ROOT/../.. -Dlogback.configurationFile=file:$TOOL_ROOT/../../conf/logback.xml -classpath $CLASSPATH com.hp.snap.gr.cmd.JMXCommandLine -spaceEscape ^ -jmxBeanName $1/$2/ATOM:type=Server,name=ATOM^Server -jmxAttributeName Status 2>/dev/null)
    if [[ $RESULT_SERVER != STARTING && $RESULT_SERVER != ACTIVE && $RESULT_SERVER != STOPPING ]] ; then
        echo "$RESULT_SERVER"
        RESULT_SERVER=IDLE
    fi
    if [ $3 = "output" ] ; then
        OUTPUT="$OUTPUT\"server_status\":\"$RESULT_SERVER\"" #output
    fi
}

# OUTPUT: add server_status and biz_service_status for each session server
getSessionServerStatus(){
    local result=$($JAVA_HOME/bin/java -DGRHome=$TOOL_ROOT/../.. -Dlogback.configurationFile=file:$TOOL_ROOT/../../conf/logback.xml -classpath $CLASSPATH com.hp.snap.gr.cmd.GetSessionServerStatusCMD $OUTPUT 2>/dev/null)
    OUTPUT=$result
}



# $1: host
# $2: session server name
startIUMSS()
{
    RESULT=`$EIUM_HOME/bin/processmanager $EIUM_SECURITY start /deployment/$1/$2  | grep -v grep | grep successfully`
    showResultYesNo "SNAP Subsystem $1 $2 is starting? > " $RESULT
}

startIUMSSOptimal()
{
   echo "processmanager date:"
   date
   $EIUM_HOME/bin/processmanager < $PARAM_FILE > $RESULT_FILE
   echo "processmanager date:"
   date
   cat $RESULT_FILE
}

stopIUMSSOptimal()
{
   echo "processmanager date:"
   date
   $EIUM_HOME/bin/processmanager < $PARAM_FILE > $RESULT_FILE
   echo "processmanager date:"
   date
   cat $RESULT_FILE
}

# $1: host
# $2: session server name
# $3: timeout in sec.
waitForSessionServerStarting()
{
    TIME_START=$(date "+%s")

    echo -n "Checking start status for $1 $2 ..."
    counter=0
    RESULT=1
    while [ $RESULT = 1 ]; do
        #if [ $counter -gt $(($3/2)) ] ; then
            checkServerStatus $1 $2 "output-no"
            if [ "$RESULT_SERVER" = "ACTIVE" ] ; then
                RESULT=0
            fi
        #fi

        printf ..
        counter=$(($counter+2))
        if [ $counter -gt $3 ];then
            echo "Session Server $1/$2 start timeout in $3 seconds, please check status..."
            checkServerStatus $1 $2 output
            return
        fi
        sleep 2
    done

    checkServerStatus $1 $2 output

    TIME_NOW=$(date "+%s")
    TIME=$((TIME_NOW-TIME_START))
    echo "Started in $TIME seconds."
}

waitForSessionServerStartingOptimal()
{
   local result=$($JAVA_HOME/bin/java -DGRHome=$TOOL_ROOT/../.. -Dlogback.configurationFile=file:$TOOL_ROOT/../../conf/logback.xml -classpath $CLASSPATH com.hp.snap.gr.cmd.GetStartSessionServerStatusCMD $OUTPUT $TIMEOUT 2>/dev/null)
    OUTPUT=$result
}

# $1: host
# $2: session server name
stopIUMSS()
{
    RESULT=`$EIUM_HOME/bin/processmanager $EIUM_SECURITY stop /deployment/$1/$2  | grep -v grep | grep successfully`
    showResultYesNo "SNAP Subsystem $1 $2 is stopped? > " $RESULT
    checkServerStatus $1 $2 output
}

# $1: host
# $2: session server name
checkIUMSS()
{
echo "processmanager date:"
date
    RESULT=`$EIUM_HOME/bin/processmanager $EIUM_SECURITY show /deployment/$1/$2  | grep -v grep | grep 'Process has started'`
    showResultYesNo "SNAP Subsystem $1 $2 running? > " $RESULT
echo "processmanager date end:"
date
}
###############################
checkIUMSSOptimal()
{
echo "processmanager date:"
date
   $EIUM_HOME/bin/processmanager < $PARAM_FILE > $RESULT_FILE
echo "processmanager date end:"
date    
}
###############################
checkIUMSS2()
{
  session_desc=/deployment/$1/$2
  line=`grep -n "show ${session_desc}" ${RESULT_FILE} | awk -F: '{print $1}'`
  line=$(($line+2))
  status=`sed -n "${line}p" ${RESULT_FILE}`
  echo $status
}

#########
startAll()
{
    OUTPUT="{" #output

    echo "======= Checking session servers: ${SESSION_SERVERS[*]} ..."
    OUTPUT=$OUTPUT"\"results\":[" #output-results
	
    local EntryCount=${#SESSION_SERVERS[@]}
    local i
    #rm -f .starting
	initParamFile
	for (( i=0; i<$EntryCount; i++ )) ; do
        local hostname=`echo ${SESSION_SERVERS[$i]} | awk -F/ '{print $2}'`
        local ssname=`echo ${SESSION_SERVERS[$i]} | awk -F/ '{print $3}'`
		echo "show /deployment/$hostname/$ssname" >> $PARAM_FILE
    done
	
	echo "exit" >> $PARAM_FILE
	
	checkIUMSSOptimal
	initParamFile
    for (( i=0; i<$EntryCount; i++ )) ; do
        echo "--------------------"
       # OUTPUT=$OUTPUT"{\"session_server\":\""${SESSION_SERVERS[$i]}"\"," #output
        local hostname=`echo ${SESSION_SERVERS[$i]} | awk -F/ '{print $2}'`
        local ssname=`echo ${SESSION_SERVERS[$i]} | awk -F/ '{print $3}'`
        
        #checkIUMSS $hostname $ssname
		RESULT_STATUS=`checkIUMSS2 $hostname $ssname`
		MSG=`echo $RESULT_STATUS | grep 'Process has started'`
		showResultYesNo "SNAP Subsystem $hostname $ssname running? > " $MSG
        if [ "$MSG" = "" ] ; then
		    
		    OUTPUT=$OUTPUT"{\"session_server\":\""${SESSION_SERVERS[$i]}"\"," #output
            OUTPUT="$OUTPUT\"state\":\"Stopped\"," #output
			 OUTPUT=$OUTPUT"}," #output
			echo "start /deployment/$hostname/$ssname" >> $PARAM_FILE
			
            #startIUMSS $hostname $ssname $TIMEOUT
            #sleep $START_DELAY
           # echo "waitForSessionServerStarting $hostname $ssname $TIMEOUT" >> .starting
       # else
         #   OUTPUT="$OUTPUT\"state\":\"Running\"" #output
        fi
		
       # OUTPUT=$OUTPUT"}," #output
    done
    
    OUTPUT="$OUTPUT]" #output-results

    OUTPUT=$OUTPUT"}" #output
	echo "exit" >> $PARAM_FILE
	echo "Starting session servers................."
	startIUMSSOptimal
	echo "Checking status of starting session server......"
	waitForSessionServerStartingOptimal
    
  #  if [ -f .starting ] ; then
  #      while read LINE
  #      do
  #          $LINE
  #      done < .starting
  #      rm -f .starting
  #  fi
    echo $OUTPUT #output
}

stopAll()
{
    OUTPUT="{" #output-start

    echo "======= Checking session servers: ${SESSION_SERVERS[*]} ..."
    OUTPUT=$OUTPUT"\"results\":[" #output-results

    local EntryCount=${#SESSION_SERVERS[@]}
    local i
	initParamFile
	for (( i=0; i<$EntryCount; i++ )) ; do
        local hostname=`echo ${SESSION_SERVERS[$i]} | awk -F/ '{print $2}'`
        local ssname=`echo ${SESSION_SERVERS[$i]} | awk -F/ '{print $3}'`
		echo "show /deployment/$hostname/$ssname" >> $PARAM_FILE
    done
	echo "exit" >> $PARAM_FILE
	
	checkIUMSSOptimal
	initParamFile
	
    for (( i=0; i<$EntryCount; i++ )) ; do
      #  echo "-------------------- Check ${SESSION_SERVERS[$i]} status......"
        OUTPUT=$OUTPUT"{\"session_server\":\""${SESSION_SERVERS[$i]}"\"," #output
        local hostname=`echo ${SESSION_SERVERS[$i]} | awk -F/ '{print $2}'`
        local ssname=`echo ${SESSION_SERVERS[$i]} | awk -F/ '{print $3}'`

        #checkIUMSS $hostname $ssname
		RESULT_STATUS=`checkIUMSS2 $hostname $ssname`
		MSG=`echo $RESULT_STATUS | grep 'Process has started'`
		showResultYesNo "SNAP Subsystem $hostname $ssname running? > " $MSG
        if [ "$MSG" = "" ] ; then
            OUTPUT="$OUTPUT\"state\":\"Stopped\"" #output
            echo "SNAP Subsystem ${SESSION_SERVERS[$i]} is already stopped."
        else
            OUTPUT="$OUTPUT\"state\":\"Running\"," #output
			echo "stop /deployment/$hostname/$ssname" >> $PARAM_FILE
           # stopIUMSS $hostname $ssname
        fi
        OUTPUT=$OUTPUT"}," #output
    done

    OUTPUT="$OUTPUT]" #output-results

    OUTPUT=$OUTPUT"}" #output-end
	
	echo "exit" >> $PARAM_FILE
	echo "Stopping session servers................."
	stopIUMSSOptimal
    #echo $OUTPUT #output
   echo "Stop all session servers completed."
}

status()
{
    initParamFile
    OUTPUT="{" #output

    echo "======= Checking session servers: ${SESSION_SERVERS[*]} ..."
    OUTPUT=$OUTPUT"\"results\":[" #output-results

    local EntryCount=${#SESSION_SERVERS[@]}
    local i
    for (( i=0; i<$EntryCount; i++ )) ; do
        local hostname=`echo ${SESSION_SERVERS[$i]} | awk -F/ '{print $2}'`
        local ssname=`echo ${SESSION_SERVERS[$i]} | awk -F/ '{print $3}'`
		echo "show /deployment/$hostname/$ssname" >> $PARAM_FILE
    done
	
	echo "exit" >> $PARAM_FILE
	
	checkIUMSSOptimal
	
	for (( i=0; i<$EntryCount; i++ )) ; do
        echo "-------------------- check ${SESSION_SERVERS[$i]}"
        OUTPUT=$OUTPUT"{\"session_server\":\""${SESSION_SERVERS[$i]}"\"," #output
        local hostname=`echo ${SESSION_SERVERS[$i]} | awk -F/ '{print $2}'`
        local ssname=`echo ${SESSION_SERVERS[$i]} | awk -F/ '{print $3}'`
	
    	RESULT_STATUS=`checkIUMSS2 $hostname $ssname`
		MSG=`echo $RESULT_STATUS | grep 'Process has started'`
		if [ "$MSG" != "" ] ; then
            OUTPUT="$OUTPUT\"state\":\"Running\"," #output
        else
            OUTPUT="$OUTPUT\"state\":\"Stopped\"" #output
        fi
        OUTPUT=$OUTPUT"}," #output
    done
	

    OUTPUT="$OUTPUT]" #output-results

    OUTPUT=$OUTPUT"}" #output-end

    getSessionServerStatus # output-add server_status and biz_service_status for each session server

    echo $OUTPUT #output
}

setStatus()
{
    local result=$($JAVA_HOME/bin/java -DGRHome=$TOOL_ROOT/../.. -Dlogback.configurationFile=file:$TOOL_ROOT/../../conf/logback.xml -classpath $CLASSPATH com.hp.snap.gr.cmd.SetSiteBizServiceStatusCMD ${SESSION_SERVERS[*]} $BIZ_SERVICE_STATUS 2>/dev/null)
    echo "$result" #output
}

########################## Main
# $1- command name
# $2- content of properties file
case "$1" in
    startAll|stopAll)
        echo "======= Read Properties ==========================="
        readProperty "$2"
        $1
        ;;

    restartAll)
        echo "======= Read Properties ==========================="
        readProperty "$2"
        stopAll
        startAll
        ;;

    status)
        echo "======= Read Properties ==========================="
        readProperty "$2"
        $1
        ;;

    setStatus)
        echo "======= Read Properties ==========================="
        readProperty "$2"
        $1
        ;;

      *)
        echo "Usage: $1 status|startAll|stopAll $2 properties"
        exit 1
esac
